package com.lstimeline.servlet;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.lstimeline.utility.Validation;
import com.lstimeline.utility.DataManager.LoginDataManager;
import com.lstimeline.bean.UserBean;

 public class LoginServlet extends HttpServlet {
	 
	private static final long serialVersionUID = 1L;
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		LoginDataManager.loadDriver();
	}
	
	//A helper method that forwards the request to login.jspx
	private void redirectToViewer(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/login.jspx");
		dispatcher.forward(request, response);
	}
	
	//A helper method that handles login errors
	private void loginError(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String errorMessage = "The username/password combination can not be found.";
		request.setAttribute("errorMessage", errorMessage);
		redirectToViewer(request,response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		redirectToViewer(request,response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String username = request.getParameter("martinet");
		String password = request.getParameter("animalcule");
		
		// Principle of distrust: all user inputs should be considered malicious
		// check for empty, abnormal inputs
		if(!Validation.isUsernameWellFormed(username) || 
		   !Validation.isPasswordWellFormed(password)) {
			//System.out.println("Login input abnormality detected.");
			loginError(request, response);
		} else {
			UserBean userBean = LoginDataManager.getUserData(username, password);
			if(userBean != null) {
				//Successful Login
				HttpSession session = request.getSession();
				session.setAttribute("userBean", userBean);
				//TODO send to referer?
				response.sendRedirect("/"); //relative to the server container route
			} else {
				//System.out.println("Account record not found.");
				loginError(request, response);
			}
		}
	}
}